package rin.cq.tho;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.EventLog;
import android.util.Log;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.material.snackbar.Snackbar;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.crashreport.CrashReport;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressBar;
    String tho_web="https://cqtho.club/";
    String TAG="重庆 THO 主界面";
    long picDownId;
    long exitTime = 0;

    //一切的初始
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e(TAG,"这个Android设备的机型是："+ Build.DEVICE+"，设备代号是："+Build.BOARD);
        Bugly.init(getApplicationContext(),"858a9a1f17",false);
        webview=findViewById(R.id.web_view);
        progressBar=findViewById(R.id.web_progress);
        loadDefaultWebSettings();
        webview.loadUrl(tho_web);
        webview.setWebViewClient(new WebClient());
        webview.setWebChromeClient(new ChromeClient());
        webview.setLongClickable(true);
        webview.setOnLongClickListener(new WebViewLongClickFunc());
    }


    //这是默认的WebSettings，以后作为shared_prefs存储
    private void loadDefaultWebSettings(){
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);// 是否开启JS支持
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    }

    private class WebViewLongClickFunc implements View.OnLongClickListener{
        @Override
        public boolean onLongClick(View v) {
            //设置的网页长按选项
            WebView.HitTestResult result = webview.getHitTestResult();
            if(result.getType()== WebView.HitTestResult.IMAGE_TYPE||
            result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE){
                Snackbar.make(v,R.string.action_save_question,Snackbar.LENGTH_LONG)
                        .setAction(R.string.action_save_text,new SavePicAction())
                        .show();
            }else{
                return false;
            }
            return true;
        }
    }

    private class SavePicAction implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            WebView.HitTestResult result = webview.getHitTestResult();
            String picture = result.getExtra();
            String picName = System.currentTimeMillis() + "_重庆_THO.jpg";
            requestPermission();
            setReceiver();
                try {
                    DownloadManager dlmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                    Uri uri = Uri.parse(picture);
                    DownloadManager.Request requestPicDown = new DownloadManager.Request(uri);
                    requestPicDown.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, picName);
                    requestPicDown.allowScanningByMediaScanner();
                    requestPicDown.setVisibleInDownloadsUi(true);
                    requestPicDown.setTitle(getString(R.string.down_manager_title));
                    requestPicDown.setDescription(getString(R.string.down_manager_desc));
                    requestPicDown.setMimeType("image/jpeg");
                    requestPicDown.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    picDownId = dlmanager.enqueue(requestPicDown);
                    Log.e(TAG, "Download OK :" + picDownId);
                } catch (Exception e) {
                    //下载出错时打开Intent调用系统下载器且上报给Bugly
                    Log.e(TAG, "Download err...");
                    CrashReport.getDeviceID(getApplicationContext());
                    CrashReport.getAppVer();
                    CrashReport.getUserId();
                    CrashReport.postCatchedException(e);
                    Uri uri = Uri.parse(picture);
                    //String android.intent.action.VIEW 比较通用，会根据用户的数据类型打开相应的Activity。如:浏览器,电话,播放器,地图
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            Log.e(TAG,"图片URL是"+picture+"，保存文件名为"+picName);
        }
    }

    //处理按下返回键时如果网页可以回退则回退，否时则退出App
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if(webview.canGoBack()) {
                webview.goBack();
                Log.d(TAG, "WebView go back");
                return true;
            }else{
                if((System.currentTimeMillis()-exitTime) > 2000){
                    Snackbar.make(webview,R.string.action_2_tap_exit,Snackbar.LENGTH_LONG).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    //退出代码
                    webview.destroy();
                    finish();
                    Log.d(TAG,"WebView and Apps are destroyed!");
                }
                return true;
            }
        }
        //当设备是Google Android Emulator（机型代号goldfish）和我的红米Note 10 Pro时允许进入Bugly测试界面
        if(keyCode==KeyEvent.KEYCODE_MENU ){
            if (Build.BOARD.equals("chopin")||Build.BOARD.equals("goldfish_x86_64")||Build.BOARD.equals("goldfish_x86")) {
                Intent bugly = new Intent(MainActivity.this, BuglyTest.class);
                startActivity(bugly);
            }else{
                Log.e(TAG,Build.BOARD+"不是测试设备！");
                Snackbar.make(webview,Build.BOARD+getString(R.string.action_not_debug_device),Snackbar.LENGTH_LONG).show();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //WebViewClient的各项设置
    private class WebClient extends WebViewClient{
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            progressBar.setVisibility(View.VISIBLE);
            setTitle(R.string.load_title);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            setTitle(webview.getTitle());
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);

        }

        //拦截私有协议然后传递给app
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);
            Log.e(TAG,"URL Scheme是"+uri.getScheme()+"，URL是"+url);
                if(!url.startsWith("http://") && !url.startsWith("https://")){
                    Snackbar.make(webview,R.string.action_jump_request,Snackbar.LENGTH_LONG)
                            .setAction(R.string.action_jump_req_btn, v -> {
                                try{
                                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                                    startActivity(intent);
                                }catch (Exception e){
                                    //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                                    CrashReport.postCatchedException(e);
                                    Snackbar.make(webview,R.string.action_jump_failed,Snackbar.LENGTH_LONG).show();
                                }
                            })
                            .show();
                    return true;
                }
                webview.loadUrl(url);
                return true;
        }
    }


    //WebChromeClient部分的设置
    private class ChromeClient extends WebChromeClient{
        @Override
        public void onProgressChanged(WebView view,int newProgress){
            progressBar.setProgress(newProgress);
            if(newProgress==100){
                progressBar.setVisibility(View.GONE);
                setTitle(webview.getTitle());
            }
            super.onProgressChanged(view,newProgress);
        }

    }

    //保存图片的时候请求存储权限
    public void requestPermission() {
        Log.e(TAG,"请求权限");
        //判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限.它在用户选择"不再询问"的情况下返回false
                Snackbar.make(webview,R.string.action_request_perm,Snackbar.LENGTH_LONG)
                        .setAction(R.string.action_request_btn, v -> ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 1))
                        .show();
            } else {
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }
    }

    //下载器注册的广播
    private void setReceiver() {
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if ( picDownId == reference) {
                    Snackbar.make(webview,R.string.action_download_ok,Snackbar.LENGTH_LONG).show();
                }
            }
        };
        registerReceiver(receiver, filter);
    }
}